package com.hmdp.utils;

import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {

    private final String name;
    private final StringRedisTemplate stringRedisTemplate;
    private static final String KEY_PREFIX = "lock:";

    // 释放锁的Lua脚本
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
    // 生成唯一标识，解决分布式环境下线程ID重复问题
    private final String identifier;

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
        // 结合UUID和线程ID，确保分布式环境下的唯一性
        this.identifier = UUID.randomUUID().toString() + "-" + Thread.currentThread().getId();
    }

    @Override
    public boolean tryLock(Long timeoutSec) {
        // 设置锁时存入唯一标识
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(
                KEY_PREFIX + name,
                identifier,
                timeoutSec,
                TimeUnit.SECONDS
        );
        return Boolean.TRUE.equals(flag);
    }

    @Override
    public void unLock() {
        // 使用Lua脚本原子性校验并释放锁
/*        String script = "if redis.call('get', KEYS[1]) == ARGV[1] then " +
                "return redis.call('del', KEYS[1]) " +
                "else " +
                "return 0 " +
                "end";*/
        stringRedisTemplate.execute(
                UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                identifier
        );
    }
}
